<?php
/**
 * 注释不留名，代码随便用
 * Date: 2019/4/17
 * Time: 15:34
 */

namespace app\common\traits;

use think\Db;
use think\Exception;
use think\Model;

trait TableSelect
{
    public function tableSelect()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d');
        $fields = input('fields/s');
        $engine = $this->model ? $this->model->db() :  Db::name($this->table);
        $keywords = input('keywords/s');
        $where = input('where/s');
        $table_search = isset($this->table_search) ? $this->table_search : $fields;
        $table_search = is_array($table_search) ? $table_search : explode(',', $table_search);
        if (!empty($keywords)) {
            foreach ($table_search as $field) {
                $engine->whereOr($field, 'like', '%' . $keywords . '%');
            }
        }
        if($where){
            $engine->where($where);
        }
        $engine->field($fields);
        $paginate = $engine->paginate($limit, false, [
            'page' => $page,
            'query' => request()->get()
        ]);
        $data = [];
        $data['list'] = $paginate->items();
        $this->callback('_page_filter', $data['list']);
        //添加统计数
        $data['count'] = $paginate->total();
        return json([
            'code' => 1,
            'msg' => '',
            'data' => $data,
        ]);
    }
}